import { CacheService } from '@app/cache';
import { BaseService } from '@app/db/base/base.service';
import { User } from '@app/db/entities/User';
import { UserWalletLog } from '@app/db/entities/UserWalletLog';
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, DataSource, FindOptionsWhere, LessThan, ObjectLiteral } from 'typeorm';
import { WechatService } from '../wechat/wechat.service';

@Injectable()
export class UserService extends BaseService<User>{
    private readonly prefix = 'user:';
    constructor(
        @InjectRepository(User) protected repository:Repository<User>,
        @InjectRepository(UserWalletLog) protected userWalletLog:Repository<UserWalletLog>,
        public dataSource: DataSource,
        private cache:CacheService,
        private wechat:WechatService,
    ) {
        super()
        this.primaryKey = 'id'
    }


    setCache(id:number, user:any) {
        return this.cache.hmset(this.prefix + id, user)
    }

    getFromCache(id:number) {
        return this.cache.hgetall(this.prefix + id)
    }

    async getUserAvailableBalance(userId:number) {
        const user = await this.findOne({id : userId}, ['amount', 'rewardAmount'])
        return user ? (Number(user.amount) + Number(user.rewardAmount)) : 0
    }

    async getUserBalance(userId) {
        return this.findOne({id : userId}, ['amount', 'rewardAmount'])
    }


    async balanceRecord(query:Pagination, userId:number) {
        let where:FindOptionsWhere<UserWalletLog> = { userId }
        const lastId = query.lastKey || 0
        const pageSize = query.pageSize || 20

        if(lastId > 0) {
            where.id = LessThan(lastId)
        }

        let rows:UserWalletLog[] = await this.userWalletLog.find({
            where,
            skip : 0, 
            take : pageSize, 
            order : {id : 'DESC'}
        })

        return rows
    }


    async payscorePermissions(userId:number, data, isWx:boolean) {
        const lockKey= 'p:p:' + userId
        const lock = await this.cache.set(lockKey, '1', 20, 'NX')
        if(!lock) return false

        if(isWx) {
            try {
                const res = await this.wechat.decipher_gcm(data.ciphertext, data.associated_data, data.nonce)
                const status = res.user_service_status == 'USER_OPEN_SERVICE' ? 1 : 0
                this.repository.update({id : userId}, {payscore : status})
                this.cache.del(lockKey)

                return true

            } catch (error) {
                
                console.log(error)
                
            }

            return false
           
        }else { //支付宝

        }


    }
    
}
